/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.smartloli.kafka.eagle.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.smartloli.kafka.eagle.application.dto.BrokerGraph;
import org.smartloli.kafka.eagle.application.dto.DashboardDisplayInfo;
import org.smartloli.kafka.eagle.application.dto.KafkaTopicInfo;
import org.smartloli.kafka.eagle.application.dto.metric.KpiInfo;
import org.smartloli.kafka.eagle.application.dto.topic.KafkaBrokerInfo;
import org.smartloli.kafka.eagle.application.dto.topic.TopicLogSize;
import org.smartloli.kafka.eagle.application.dto.topic.TopicRank;
import org.smartloli.kafka.eagle.application.service.ConsumerService;
import org.smartloli.kafka.eagle.application.service.DashboardService;
import org.smartloli.kafka.eagle.config.KafkaClustersConfig;
import org.smartloli.kafka.eagle.domain.service.BrokerService;
import org.smartloli.kafka.eagle.domain.service.KafkaService;
import org.smartloli.kafka.eagle.infra.constant.KafkaConstants;
import org.smartloli.kafka.eagle.infra.constant.TopicConstants;
import org.smartloli.kafka.eagle.infra.mapper.MBeanDao;
import org.smartloli.kafka.eagle.infra.mapper.TopicDao;
import org.smartloli.kafka.eagle.infra.query.TopicRankQuery;
import org.smartloli.kafka.eagle.infra.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Kafka Eagle dashboard data generator.
 * 
 * @author smartloli.
 *
 *         Created by Aug 12, 2016.
 * 
 *         Update by hexiang 20170216
 */
@Service
public class DashboardServiceImpl implements DashboardService {

	/** Kafka service interface. */
	@Autowired
	private KafkaService kafkaService;

	/** Broker service interface. */
	@Autowired
	private BrokerService brokerService;

    @Autowired
    private TopicDao topicDao;

    @Autowired
    private MBeanDao mbeanDao;

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private KafkaClustersConfig kafkaClustersConfig;

    /**
     * Get consumer number from zookeeper.
     */
    private int getConsumerNumbers(String clusterAlias) {
        Map<String, List<String>> consumers = consumerService.getConsumers(clusterAlias);
        int count = 0;
        for (Entry<String, List<String>> entry : consumers.entrySet()) {
            count += entry.getValue().size();
        }
        return count;
    }

	/** Get kafka & dashboard dataset. */
	public DashboardDisplayInfo getDashboard(String clusterAlias) {
        DashboardDisplayInfo dashboardDisplayInfo = new DashboardDisplayInfo();

        List<KafkaBrokerInfo> brokers = kafkaService.getBrokerInfos(clusterAlias);
        BrokerGraph kafkaBrokersGraph = new BrokerGraph();
        List<JSONObject> brokerHostInfos = new ArrayList<>();
        int count = 0;
        for (KafkaBrokerInfo broker : brokers) {
            //Control Kafka Broker Display Num
            JSONObject jsonObject = new JSONObject();
            if (count > KafkaConstants.SIZE) {
                jsonObject.put("name", "...");
                break;
            } else {
                jsonObject.put("name",broker.getHost() + ":" + broker.getPort());
            }
            brokerHostInfos.add(jsonObject);
            count++;
        }
        kafkaBrokersGraph.setChildren(brokerHostInfos);
        dashboardDisplayInfo.setGraph(kafkaBrokersGraph);

        int zks = kafkaClustersConfig.getClusterConfigByName(clusterAlias).getZkList().split(",").length;
        dashboardDisplayInfo.setBrokers(brokerService.brokerNumbers(clusterAlias));
        dashboardDisplayInfo.setTopics(brokerService.topicNumbers(clusterAlias));
        dashboardDisplayInfo.setZks(zks);
        String formatter = kafkaClustersConfig.getClusterConfigByName(clusterAlias).getOffsetStorage();
        if (KafkaConstants.KAFKA.equals(formatter)) {
            dashboardDisplayInfo.setConsumers(consumerService.getKafkaConsumerGroups(clusterAlias).size());
        } else {
            dashboardDisplayInfo.setConsumers(getConsumerNumbers(clusterAlias));
        }
		return dashboardDisplayInfo;
	}

	/** Get topic rank data,such as logsize and topic capacity. */
	@Override
	public List<KafkaTopicInfo> getTopicRank(TopicRankQuery topicRankQuery) {
		List<TopicRank> topicRank = topicDao.readTopicRank(topicRankQuery);
        List<KafkaTopicInfo> kafkaTopicInfos = new ArrayList<>();
		if (TopicConstants.LOGSIZE.equals(topicRankQuery.getTkey())) {
			int index = 1;
			for (int i = 0; i < 10; i++) {
				KafkaTopicInfo kafkaTopicInfo = new KafkaTopicInfo();
				if (i < topicRank.size()) {
                    kafkaTopicInfo.setId(index);
                    kafkaTopicInfo.setName( "<a href='/topic/meta/page/" + topicRank.get(i).getTopic() + "'>" + topicRank.get(i).getTopic() + "</a>");
                    kafkaTopicInfo.setLogSize(topicRank.get(i).getTvalue().toString());
                } else {
                    kafkaTopicInfo.setId(index);
				}
				index++;
                kafkaTopicInfos.add(kafkaTopicInfo);
			}
		} else if (TopicConstants.CAPACITY.equals(topicRankQuery.getTkey())) {
			int index = 1;
			for (int i = 0; i < 10; i++) {
                KafkaTopicInfo kafkaTopicInfo = new KafkaTopicInfo();
				if (i < topicRank.size()) {
                    kafkaTopicInfo.setId(index);
                    kafkaTopicInfo.setName( "<a href='/topic/meta/page/" + topicRank.get(i).getTopic() + "'>" + topicRank.get(i).getTopic() + "</a>");
                    kafkaTopicInfo.setCapacity(topicRank.get(i).getTvalue().toString());
                } else {
                    kafkaTopicInfo.setId(index);
				}
				index++;
                kafkaTopicInfos.add(kafkaTopicInfo);
			}
		}
		return kafkaTopicInfos;
	}

	/** Write statistics topic rank data from kafka jmx & insert into table. */
	public int writeTopicRank(List<TopicRank> topicRanks) {
        return topicDao.writeTopicRank(topicRanks);
    }

    /**
     * Write statistics topic logsize data from kafka jmx & insert into table.
     */
    public int writeTopicLogSize(List<TopicLogSize> topicLogSize) {
        return topicDao.writeTopicLogSize(topicLogSize);
    }

    @Override
    public JSONObject getOSMem(Map<String, Object> params) {
        List<KpiInfo> kpis = mbeanDao.getOsMem(params);

        //avoid metric value is empty
        kpis.removeIf(kpi -> null == kpi || null == kpi.getValue());

        JSONObject object = new JSONObject();
        object.put("mem", 0.0);
        if (kpis.size() == 2) {
            long valueFirst = Long.parseLong(kpis.get(0).getValue());
            long valueSecond = Long.parseLong(kpis.get(1).getValue());
            if (valueFirst >= valueSecond && valueFirst != 0L) {
                object.put("mem", 100 * StrUtils.numberic((valueFirst - valueSecond) * 1.0 / valueFirst, "###.###"));
            } else if (valueSecond != 0L) {
                object.put("mem", 100 * StrUtils.numberic((valueSecond - valueFirst) * 1.0 / valueSecond, "###.###"));
            }
        }
        return object;
    }

	/** Read topic lastest logsize diffval data. */
	public TopicLogSize readLastTopicLogSize(Map<String, Object> params) {
		return topicDao.readLastTopicLogSize(params);
	}

	/** Get all clean topic list. */
	public List<TopicRank> getCleanTopicList(Map<String, Object> params) {
		return topicDao.getCleanTopicList(params);
	}

}